package com.dbh.alg.datastructure.queue;

import java.util.Iterator;

/**
 * 对列-环形数组实现
 * @author dongbanghui
 * @date 2025/5/15
 */
public class ArrayQueue<E> implements Queue<E>, Iterable<E> {

    private E[] array;
    private int head = 0;
    private int tail = 0;

    public ArrayQueue(int capacity) {
        array = (E[]) new Object[capacity + 1];
    }

    /**
     * 向对列尾插入值
     *
     * @param value -待插入值
     * @return 插入成功返回true，插入失败返回false
     */
    @Override
    public boolean offer(E value) {
        if (isFull()) {
            return false;
        }
        array[tail] = value;
        tail = (tail + 1) % array.length;
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        E value = array[head];
        head = (head + 1) % array.length;
        return value;
    }

    /**
     * 从对列头获取值，不移除
     *
     * @return 如果队列非空返回对头值，否则返回null
     */
    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return array[head];
    }

    /**
     * 检查对列是否为空
     *
     * @return 空返回true，否则返回false
     */
    @Override
    public boolean isEmpty() {
        if (head == tail) {
            return true;
        }
        return false;
    }

    /**
     * 检查对列是否已满
     *
     * @return 满返回true，否则返回false
     */
    @Override
    public boolean isFull() {
        return  (tail + 1) % array.length == head;
    }

    /**
     * Returns an iterator over elements of type {@code T}.
     *
     * @return an Iterator.
     */
    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = head;
            @Override
            public boolean hasNext() {
                return p != tail;
            }

            @Override
            public E next() {
                E value = array[p];
                p = (p + 1) % array.length;
                return value;
            }
        };
    }
}
